package com.kzj.laimeimei.fragment;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.kzj.laimeimei.R;
import com.kzj.laimeimei.activity.EvaluationOrderActivity;
import com.kzj.laimeimei.activity.GBaseActivity;
import com.kzj.laimeimei.activity.LoginActivity;
import com.kzj.laimeimei.beans.CloseActivityBean;
import com.kzj.laimeimei.beans.OrderBean;
import com.kzj.laimeimei.global.App;
import com.kzj.laimeimei.global.Constant;
import com.kzj.laimeimei.recyclerCard.basic.MaterialListView;
import com.kzj.laimeimei.recyclerCard.basic.OnButtonPressListener;
import com.kzj.laimeimei.recyclerCard.basic.SuperSwipeRefresh;
import com.kzj.laimeimei.recyclerCard.card.Card;
import com.kzj.laimeimei.recyclerCard.card.other.GoToLoginCard;
import com.kzj.laimeimei.recyclerCard.card.other.LoadingCard;
import com.kzj.laimeimei.recyclerCard.card.other.NotNetCard;
import com.kzj.laimeimei.recyclerCard.card.other.NotOrderCard;
import com.kzj.laimeimei.recyclerCard.card.other.OrderCard;
import com.kzj.laimeimei.recyclerCard.cardView.ServiceOrderCardView;
import com.kzj.laimeimei.request.BaseResponse;
import com.kzj.laimeimei.request.ICallBackForRequestServer;
import com.kzj.laimeimei.request.RequestServerManager;
import com.kzj.laimeimei.widget.dialog.SweetDialogManager;
import com.kzj.laimeimei.wxapi.WXPayEntryActivity;

import java.util.List;

import cn.pedant.SweetAlert.SweetAlertDialog;
import de.greenrobot.event.EventBus;

/**
 * Created by xyg on 2015/10/9.
 */
public class AllOrderFragment extends BaseFragment implements SuperSwipeRefresh.OnRefreshReceyerListener, SuperSwipeRefresh.OnLoadMoreListener {
    private MaterialListView materialListView;
    private String status = "0";
    private View holderView;
    private int page = 1;
    private SuperSwipeRefresh superSwipeRefresh;
    private NotNetCard notNetCard;
    private LoadingCard loadingCard;
    private NotOrderCard notOrderCard;
    private GoToLoginCard goToLoginCard;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        if (holderView == null) {
            holderView = inflater.inflate(R.layout.template_superswiperefresh_materlistview, container, false);
            findViewByIds();
        }
        ViewGroup parent = (ViewGroup) holderView.getParent();
        if (parent != null) {
            parent.removeView(holderView);
        }
        return holderView;
    }

    @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);
    }

    @Override
    public void findViewByIds() {
        materialListView = (MaterialListView) holderView.findViewById(R.id.material_listview);
        superSwipeRefresh = (SuperSwipeRefresh) holderView.findViewById(R.id.superSwipeRefresh);
        superSwipeRefresh.setPageSize(10);
        superSwipeRefresh.setView(getActivity(), materialListView);
        superSwipeRefresh.setEnableLoadMore(true);
        superSwipeRefresh.setOnRefreshReceyerListener(this);
        superSwipeRefresh.setOnLoadMoreListener(this);
        loadingCard = new LoadingCard(getActivity());
        notNetCard = new NotNetCard(getActivity());
        notNetCard.setOnNormalButtonPressedListener(new OnButtonPressListener() {
            @Override
            public void onButtonPressedListener(View view, Card card) {
                refresh();
            }
        });
        notOrderCard = new NotOrderCard(getActivity());
        goToLoginCard = new GoToLoginCard(getActivity());
        goToLoginCard.setOnNormalButtonPressedListener(new OnButtonPressListener() {
            @Override
            public void onButtonPressedListener(View view, Card card) {
                Intent intent = new Intent(getActivity(), LoginActivity.class);
                startActivity(intent);
            }
        });
        if (App.getInstance().getUserBean() == null) {
            superSwipeRefresh.setEnableLoadMore(false);
        }
        EventBus.getDefault().register(this);
    }

    @Override
    public void initViews() {

    }

    @Override
    public void fillArrayInList() {

    }

    public void fillArrayInList(List<OrderBean> orderBeans, boolean isLoad) {
        if (!isLoad) {
            materialListView.clear();
            page = 2;
        } else {
            page++;
        }
        for (int i = 0; i < orderBeans.size(); i++) {
            OrderCard orderCard = new OrderCard(getActivity());
            orderCard.setOrderBean(orderBeans.get(i));
            orderCard.setOnNormalButtonPressedListener(new OnButtonPressListener() {
                @Override
                public void onButtonPressedListener(View view, final Card card) {
                    switch (view.getId()) {
                        case R.id.textView_complete:
                            SweetDialogManager.getInstance().showDialogByWarmTitleText((GBaseActivity) getActivity(), "完成订单",
                                    "确认订单完成吗？", true, true, new SweetAlertDialog.OnSweetClickListener() {
                                        @Override
                                        public void onClick(SweetAlertDialog sweetAlertDialog) {
                                            sweetAlertDialog.dismiss();
                                        }
                                    }, new SweetAlertDialog.OnSweetClickListener() {
                                        @Override
                                        public void onClick(SweetAlertDialog sweetAlertDialog) {
                                            sweetAlertDialog.dismiss();
                                            TaskCompleteOrder(((OrderCard) card).getOrderBean().getOrder_id());
                                        }
                                    });
                            break;
                        case R.id.textView_cancel:
                            if (((OrderCard) card).getOrderBean().getStatus().equals("11")) {
                                SweetDialogManager.getInstance().showDialogByWarmTitleText((GBaseActivity) getActivity(), "取消订单",
                                        "确定取消订单吗？", true, true, new SweetAlertDialog.OnSweetClickListener() {
                                            @Override
                                            public void onClick(SweetAlertDialog sweetAlertDialog) {
                                                sweetAlertDialog.dismiss();
                                            }
                                        }, new SweetAlertDialog.OnSweetClickListener() {
                                            @Override
                                            public void onClick(SweetAlertDialog sweetAlertDialog) {
                                                sweetAlertDialog.dismiss();
                                                TaskCancleOrder(((OrderCard) card).getOrderBean().getOrder_id());
                                            }
                                        });
                            } else {
                                SweetDialogManager.getInstance().showDialogByWarmTitleText((GBaseActivity) getActivity(), "是否取消订单？",
                                        "若取消订单，所支付款项将被返回到您的支付账户。", true, true, new SweetAlertDialog.OnSweetClickListener() {
                                            @Override
                                            public void onClick(SweetAlertDialog sweetAlertDialog) {
                                                sweetAlertDialog.dismiss();
                                            }
                                        }, new SweetAlertDialog.OnSweetClickListener() {
                                            @Override
                                            public void onClick(SweetAlertDialog sweetAlertDialog) {
                                                sweetAlertDialog.dismiss();
                                                TaskCancleOrder(((OrderCard) card).getOrderBean().getOrder_id());
                                            }
                                        });
                            }
                            break;
                        case R.id.textView_pay:
                            OrderCard orderCard = (OrderCard) card;
                            String payType = orderCard.getOrderBean().getPayment_code();
                            if (payType.equals(ServiceOrderCardView.payTypeAlipay)) {
                                ServiceOrderCardView.PayFlag = OrderFragment.PayFlag;
                                ServiceOrderCardView.TaskAlibabaPay(orderCard.getOrderBean().getOrder_id(), (GBaseActivity) getActivity());
                            } else {
                                WXPayEntryActivity.OrderUrl = orderCard.getOrderBean().getDetail_url();
                                WXPayEntryActivity.OrderId = orderCard.getOrderBean().getOrder_id();
                                WXPayEntryActivity.WXPayFlag = OrderFragment.PayFlag;
                                ServiceOrderCardView.TaskWeixinPay(orderCard.getOrderBean().getOrder_id(), (GBaseActivity) getActivity());
                            }
                            break;
                        case R.id.textView_delete:
                            SweetDialogManager.getInstance().showDialogByWarmTitleText((GBaseActivity) getActivity(), "删除订单",
                                    "确定删除订单吗？", true, true, new SweetAlertDialog.OnSweetClickListener() {
                                        @Override
                                        public void onClick(SweetAlertDialog sweetAlertDialog) {
                                            sweetAlertDialog.dismiss();
                                        }
                                    }, new SweetAlertDialog.OnSweetClickListener() {
                                        @Override
                                        public void onClick(SweetAlertDialog sweetAlertDialog) {
                                            sweetAlertDialog.dismiss();
                                            TaskDeleteOrder(((OrderCard) card).getOrderBean().getOrder_id());
                                        }
                                    });
                            break;
                        case R.id.textView_evaluation:
                            Intent intent = new Intent(getActivity(), EvaluationOrderActivity.class);
                            intent.putExtra("order_bean", ((OrderCard) card).getOrderBean());
                            startActivity(intent);
                            break;
                    }
                }
            });
            materialListView.add(orderCard);
        }
        if (orderBeans.size() == 0 && !isLoad) {
            materialListView.add(notOrderCard);
        }
    }

    public void onEventMainThread(CloseActivityBean closeActivityBean) {
        refresh();
    }

    private void TaskGetOrderList(String page, String status, final boolean isLoad) {
        RequestServerManager.getInstance().handleMethod(null, materialListView, superSwipeRefresh, isLoad,
                Constant.getRootUrl() + Constant.Action.Action_Order_List, RequestServerManager.getInstance().
                        getRequestParams(Constant.Action.Action_Order_List, page, status), BaseResponse.class, new ICallBackForRequestServer<BaseResponse>() {
                    @Override
                    public void onSuccess(BaseResponse result) {
                        JSONObject jsonObject = (JSONObject) result.getRetval();
                        List<OrderBean> orderBeans = JSON.parseArray(jsonObject.getString("data"), OrderBean.class);
                        fillArrayInList(orderBeans, isLoad);
                    }

                    @Override
                    public void onFail(int type, String errorMsg, String json) {
                        App.getInstance().showToast(errorMsg + "");
                        materialListView.clear();
                        materialListView.add(notNetCard);
                    }
                });
    }

    private void TaskDeleteOrder(String order_id) {
        RequestServerManager.getInstance().handleMethod((GBaseActivity) getActivity(), null, null, false,
                Constant.getRootUrl() + Constant.Action.Action_Delete_Order, RequestServerManager.getInstance().
                        getRequestParams(Constant.Action.Action_Delete_Order, order_id), BaseResponse.class, new ICallBackForRequestServer<BaseResponse>() {
                    @Override
                    public void onSuccess(BaseResponse result) {
                        App.getInstance().showToast("订单删除成功！");
                        TaskGetOrderList("1", status, false);
                    }

                    @Override
                    public void onFail(int type, String errorMsg, String json) {
                        App.getInstance().showToast(errorMsg + "");
                    }
                });
    }

    private void TaskCancleOrder(String order_id) {
        RequestServerManager.getInstance().handleMethod((GBaseActivity) getActivity(), null, null, false,
                Constant.getRootUrl() + Constant.Action.Action_Cancle_Order, RequestServerManager.getInstance().
                        getRequestParams(Constant.Action.Action_Cancle_Order, order_id), BaseResponse.class, new ICallBackForRequestServer<BaseResponse>() {
                    @Override
                    public void onSuccess(BaseResponse result) {
                        TaskGetOrderList("1", status, false);
                        App.getInstance().showToast("订单取消成功！");
                    }

                    @Override
                    public void onFail(int type, String errorMsg, String json) {
                        App.getInstance().showToast(errorMsg + "");
                    }
                });
    }

    private void TaskCompleteOrder(String order_id) {
        RequestServerManager.getInstance().handleMethod((GBaseActivity) getActivity(), null, null, false,
                Constant.getRootUrl() + Constant.Action.Action_Confirm_Order, RequestServerManager.getInstance().
                        getRequestParams(Constant.Action.Action_Confirm_Order, order_id), BaseResponse.class, new ICallBackForRequestServer<BaseResponse>() {
                    @Override
                    public void onSuccess(BaseResponse result) {
                        App.getInstance().showToast("订单确认完成！");
                        TaskGetOrderList("1", status, false);
                    }

                    @Override
                    public void onFail(int type, String errorMsg, String json) {
                        App.getInstance().showToast(errorMsg + "");
                    }
                });
    }

    public void refresh() {
        if (materialListView != null && App.getInstance().getUserBean() != null) {
            materialListView.clear();
            materialListView.add(loadingCard);
            TaskGetOrderList("1", status, false);
        }
        if (materialListView != null && App.getInstance().getUserBean() == null) {
            materialListView.clear();
            materialListView.add(goToLoginCard);
            superSwipeRefresh.setEnableLoadMore(false);
        }
    }

    public void clear() {
        if (materialListView != null && App.getInstance().getUserBean() != null) {
            materialListView.clear();
            //materialListView.add(loadingCard);
        }
    }

    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);
//        Log.i("test111111111111", "userVisiblehint--->>>" + isVisibleToUser);
//        if (isVisibleToUser) {
//            if (App.getInstance().getUserBean() != null)
//                if (materialListView != null && App.getInstance().getUserBean() != null) {
//                    materialListView.clear();
//                    materialListView.add(loadingCard);
//                    TaskGetOrderList("1", status, false);
//                }
//            if (materialListView != null && App.getInstance().getUserBean() == null) {
//                materialListView.clear();
//                materialListView.add(goToLoginCard);
//                superSwipeRefresh.setEnableLoadMore(false);
//            }
//        } else {
        if (!isVisibleToUser)
            if (materialListView != null && App.getInstance().getUserBean() != null) {
                materialListView.clear();
                //materialListView.add(loadingCard);
            }
//        }

    }

    @Override
    public void loadMore(int itemsCount, int maxLastVisiblePosition) {
        if (App.getInstance().getUserBean() != null)
            TaskGetOrderList(page + "", status, true);
    }

    @Override
    public void Refresh(MaterialListView recyclerView) {
        if (App.getInstance().getUserBean() != null)
            TaskGetOrderList(1 + "", status, false);
        else
            superSwipeRefresh.setRefreshing(false);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }
}
